YAHOO.namespace("card.entity");

var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event;

Event.onDOMReady(function () {

    if (!YAHOO.card.entity.loading) {
        // Initialize the temporary Panel to display while waiting for external content to load
        YAHOO.card.entity.loading =
            new YAHOO.widget.Panel("loading",
                { width: "240px", fixedcenter: true, close: false, draggable: false, zindex: 4, modal: true, visible: false}
            );

        YAHOO.card.entity.loading.setHeader("请等待...");
        YAHOO.card.entity.loading.setBody("<img src=\"http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif\"/>");
        YAHOO.card.entity.loading.render(document.body);
    }

    var periodTypeFormatter = function (elCell, oRecord) {
        var cardValidityPeriod = oRecord.getData('cardValidityPeriod');
        if (oRecord.getData('cardValidityPeriodType').toLowerCase() == 'y') {
            elCell.innerHTML = cardValidityPeriod + "年";
        } else if (oRecord.getData('cardValidityPeriodType').toLowerCase() == 'm') {
            elCell.innerHTML = cardValidityPeriod + "月";
        } else if (oRecord.getData('cardValidityPeriodType').toLowerCase() == 'd') {
            elCell.innerHTML = cardValidityPeriod + "日";
        } else {
            elCell.innerHTML = "";
        }
    };

    var statusFormatter = function (elCell, oRecord) {
        var cardStatus = oRecord.getData("cardStatus");
        if(cardStatus!="" && cardStatus!=undefined){
            elCell.innerHTML = messages[cardStatus];
        }else{
            elCell.innerHTML = "";
        }
    };

    var number_per_page_default = 20;
    var paginator = new YAHOO.widget.Paginator({
        containers: ['card-cards-paging'],
        rowsPerPage: number_per_page_default,
        firstPageLinkLabel: '首页',
        previousPageLinkLabel: '上一页',
        nextPageLinkLabel: '下一页',
        lastPageLinkLabel: '末页'
    });
    var tableConfig = {
        paginator: paginator,
        MSG_EMPTY: '没有记录',
        dynamicData: true,
        initialLoad: false
    };

    var columnDefs = [
        {key: "cardIndex", label: '序号'},
        {key: "cardId", label: '卡号'},
        {key: "cardType", label: '类型'},
        {key: "cardParValue", label: '星币值'},
        {key: "cardActivationDeadline", label: '截止日期'},
        {key: "cardValidityPeriodType", label: '有效期', formatter: periodTypeFormatter},
        {key: "dateAdded", label: '创建时间'},
        {key: "cardStatus", label: '状态',formatter: statusFormatter}
    ];

    var dataSource = new YAHOO.util.DataSource('/ozing/job/cards.json?');
    dataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
    dataSource.responseSchema = {
        resultsList: 'records',
        fields: ['id', 'cardId', 'cardIndex', 'active', 'cardType', 'cardParValue', 'cardActivationDeadline', 'cardValidityPeriodType', 'cardValidityPeriod',
            'dateAdded', 'cardStatus'],
        metaFields: {
            totalRecords: 'totalRecords',
            paginationRecordOffset: "startIndex",
            paginationRowsPerPage: "pageSize"
        }
    };
    var dataTable = new YAHOO.widget.DataTable("card-cards-table", columnDefs, dataSource, tableConfig);

    dataTable.showTableMessage(dataTable.get("MSG_LOADING"), YAHOO.widget.DataTable.CLASS_LOADING);

    var History = YAHOO.util.History;

    var handlePagination = function (state) {
        var newState = state.page;
        History.navigate("page", newState + "");
    };

    paginator.unsubscribe("changeRequest", dataTable.onPaginatorChangeRequest);
    paginator.subscribe("changeRequest", handlePagination, dataTable, true);

    dataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
        var meta = oResponse.meta;
        oPayload.totalRecords = meta.totalRecords || oPayload.totalRecords;
        oPayload.pagination = {
            rowsPerPage: meta.paginationRowsPerPage || number_per_page_default,
            recordOffset: meta.paginationRecordOffset || 0
        };
        return true;
    };

    var generateRequest = function (page) {
        page = page || 1;
        var batchId = $('#batchId').val();
        var start_index = (page - 1) * number_per_page_default;
        return "start_index=" + start_index + "&num_per_page=" + number_per_page_default + "&timestamp=" + new Date().getTime() + "&batchId=" + batchId;
    };

    var handleHistoryNavigation = function (page) {
        dataTable.getTbodyEl().style.display = "none";
        dataTable.showTableMessage('正在加载中，请稍候...');

        dataSource.sendRequest(generateRequest(page), {
            success: function () {
                dataTable.getTbodyEl().style.display = "";
                dataTable.hideTableMessage();
                dataTable.onDataReturnReplaceRows.apply(this, arguments);
            },
            failure: function () {
                dataTable.getTbodyEl().style.display = "";
                dataTable.hideTableMessage(YAHOO.widget.DataTable.MSG_ERROR);
                dataTable.onDataReturnReplaceRows.apply(this, arguments);
            },
            scope: dataTable,
            argument: {} // Pass in container for population at runtime via doBeforeLoadData
        });
    };

    var initialRequest = History.getBookmarkedState("page") || "1";

    History.register("page", initialRequest, handleHistoryNavigation);

    History.onReady(function () {
        renderPage();
    });

    var renderPage = function () {
        var currentState = History.getCurrentState("page");
        handleHistoryNavigation(currentState);
    };

    // Initialize the Browser History Manager.
    YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

    var handleSubmit = function () {
        this.submit();
    };
    var handleCancel = function () {
        this.cancel();
    };
    var handleSuccess = function (o) {
        renderPage();
    };
    var handleFailure = function (o) {
        alert("服务器出错");
    };

    // Instantiate agent the Dialog
    YAHOO.card.entity.agent = new YAHOO.widget.Dialog("agent",
        { width: "30em", fixedcenter: true, visible: false, constraintoviewport: true,
            buttons: [
                { text: "提交", handler: handleSubmit, isDefault: true },
                { text: "取消", handler: handleCancel }
            ]
        });

    YAHOO.card.entity.agent.validate = function () {
        var data = this.getData();
        if (!data.agent || data.agent == '') {
            alert('请输入代理商');
            return false;
        }
        var start = data.cardIndexStart;
        var end = data.cardIndexEnd;
        if (!start || !end || start == '' || end == '') {
            alert('请输入起始序号');
            return false;
        }
        if (isNaN(end) || isNaN(end)) {
            alert('请输入起始序号');
            return false;
        }
        return true;
    };
    // Instantiate  status the Dialog
    YAHOO.card.entity.status = new YAHOO.widget.Dialog("status",
        { width: "30em", fixedcenter: true, visible: false, constraintoviewport: true,
            buttons: [
                { text: "提交", handler: handleSubmit, isDefault: true },
                { text: "取消", handler: handleCancel }
            ]
        });

    YAHOO.card.entity.status.validate = function () {
        var data = this.getData();
        if (!data.status || data.status == '') {
            alert('请选择状态');
            return false;
        }
        var start = data.cardIndexStart;
        var end = data.cardIndexEnd;
        if (!start || !end || start == '' || end == '') {
            alert('请输入起始序号');
            return false;
        }
        if (isNaN(end) || isNaN(end)) {
            alert('请输入起始序号');
            return false;
        }
        return true;
    };

    YAHOO.card.entity.agent.callback = { success: handleSuccess, failure: handleFailure };
    YAHOO.card.entity.agent.render();
    YAHOO.card.entity.status.callback = { success: handleSuccess,failure: handleFailure };
    YAHOO.card.entity.status.render();

    var refresh_btn = new YAHOO.widget.Button("refresh_btn", {label: "搜索" });
    var export_btn = new YAHOO.widget.Button("export_btn", {label: "导出" });
    var lock_btn = new YAHOO.widget.Button("lock_btn", {label: "锁卡" });
    var delivery_btn = new YAHOO.widget.Button("delivery_btn", {label: "发货" });
    var status_btn = new YAHOO.widget.Button("status_btn", {label: "修改状态" });
    var unlock_btn = new YAHOO.widget.Button("unlock_btn", {label: "解锁" });
    export_btn.set('disabled', true);
    lock_btn.set('disabled', true);
    delivery_btn.set('disabled', true);
    status_btn.set('disabled', true);
    unlock_btn.set('disabled', true);
    Dom.setStyle('lock_btn', 'display', '');
    Dom.setStyle('unlock_btn', 'display', 'none');

    var validate = function (batchId) {
        if (!batchId) {alert("请选择批次号");return false;}
        return true;
    };

    YAHOO.card.entity.refresh = function () {
        var batchId = $('#batchId').val();
        if (!validate(batchId)) return;
        $('#agent_batchId').val(batchId);
        $('#status_batchId').val(batchId);
        var url = '/ozing/card/job.json';

        YAHOO.card.entity.loading.show();
        $.get(url,
            { batchId: batchId, date: new Date()},
            function (data) {

                YAHOO.card.entity.loading.hide();
                renderPage();
                if (!data['cardQuantity']) {
                    $('#cardDes').html('该批次号不存在');
                } else {
                    $('#td_batchId').html(batchId);
                    $('#td_batchStartTime').html(data['batchStartTime']);
                    $('#td_batchEndTime').html(data['batchEndTime']);
                    $('#td_cardQuantity').html(data['cardQuantity']);
                    $('#td_cardType').html(data['cardType']);
                    $('#td_cardValue').html(data['cardParValue']);
                    $('#td_cardSalePrice').html(data['cardSalePrice']);
                    $('#td_deadline').html(data['cardActivationDeadline']);
                    $('#td_cardValidityPeriod').html(data['cardValidityPeriod']);
                    $('#td_periodType').html(data['periodType']);
                    var lock;

                    if (!data['makeCardLock'] && data['cardQuantity'] > 0) {
                        lock_btn.set('disabled', false);
                        export_btn.set('disabled', false);
                        unlock_btn.set('disabled', true);
                        Dom.setStyle('lock_btn', 'display', '');
                        Dom.setStyle('unlock_btn', 'display', 'none');
                        lock = '未锁';
                    } else {
                        lock_btn.set('disabled', true);
                        export_btn.set('disabled', true);
                        unlock_btn.set('disabled', false);
                        Dom.setStyle('unlock_btn', 'display', '');
                        Dom.setStyle('lock_btn', 'display', 'none');
                        lock = '锁住';
                    }
                    $('#td_makeCardLock').html(lock);
                    $('#td_description').html(data['description']);

                    var delivery_btn = new YAHOO.widget.Button("delivery_btn", {label: "发货" });
                    var status_btn = new YAHOO.widget.Button("status_btn", {label: "修改状态" });
                    delivery_btn.set('disabled', false);
                    status_btn.set('disabled', false);
                    Event.addListener('delivery_btn', "click", YAHOO.card.entity.agent.show, YAHOO.card.entity.agent, true);
                    Event.addListener('status_btn', "click", YAHOO.card.entity.status.show, YAHOO.card.entity.status, true);
                }
            });
    };

    YAHOO.card.entity.excel = function () {
        var batchId = $('#batchId').val();
        if (!validate(batchId)) return;
        var url = '/ozing/cards/excel';
        YAHOO.card.entity.loading.show();
        $.get(url,
            { batchId: batchId},
            function (data) {
                YAHOO.card.entity.loading.hide();
            });
    };

    YAHOO.card.entity.exp = function () {
        var batchId = $('#batchId').val();
        if (!validate(batchId)) return;
        window.open("/ozing/cards/excel?batchId=" + batchId);
    };

    YAHOO.card.entity.lock = function () {
        var batchId = $('#batchId').val();
        if (!validate(batchId)) return;
        YAHOO.card.entity.loading.show();
        $.get('/ozing/cards/lock', {batchId: batchId, date: new Date()}, function () {
            YAHOO.card.entity.loading.hide();
            export_btn.set('disabled', true);
            lock_btn.set('disabled', true);
            unlock_btn.set('disabled', false);
            Dom.setStyle('lock_btn', 'display', 'none');
            Dom.setStyle('unlock_btn', 'display', '');
            $('#td_makeCardLock').html('锁住');
        });
    };

    YAHOO.card.entity.unlock = function () {
        var batchId = $('#batchId').val();
        if (!validate(batchId)) return;
        YAHOO.card.entity.loading.show();
        $.get('/ozing/cards/unlock', {batchId: batchId, date: new Date()}, function (data) {
            YAHOO.card.entity.loading.hide();
            if (data=="true") {
                export_btn.set('disabled', false);
                lock_btn.set('disabled', false);
                unlock_btn.set('disabled', true);
                Dom.setStyle('lock_btn', 'display', '');
                Dom.setStyle('unlock_btn', 'display', 'none');
                $('#td_makeCardLock').html('未锁');
            }else{
                alert("解锁失败, 只有锁定者才可以解锁.");
            }
        });
    };
    refresh_btn.on("click", YAHOO.card.entity.refresh);
    lock_btn.on("click", YAHOO.card.entity.lock);
    unlock_btn.on("click", YAHOO.card.entity.unlock);
    export_btn.on("click", YAHOO.card.entity.exp);

    return {
        ds: dataSource,
        dt: dataTable
    };

});